<?php

namespace app\common\model;

use think\Model;

/**
 * 优惠券
 */
class CouponSetting extends Model
{
    protected $name = 'coupon_setting';
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    // 追加属性
    protected $append = [

    ];

    const STATUS_OK= 1;
    const STATUS_CLOSE= 2;
    static $statusMap = [
        self::STATUS_OK => '开启',
        self::STATUS_CLOSE => "关闭",
    ];

    const TYPE_REDUCE = 1;
    static $typeMap = [
        self::TYPE_REDUCE => '立减卷',
    ];

    const RULE_DEFAULT = 0;
    const RULE_NEW = 1;
    const RULE_BIRTHDAY = 2;
    static $ruleMap = [
        self::RULE_DEFAULT => '不限',
        self::RULE_NEW => '新注用户',
        self::RULE_BIRTHDAY => '生日',
    ];

    const DATE_TYPE_SECTION = 1;
    const DATE_TYPE_FIXED = 2;
    static $dateTypeMap = [
        self::DATE_TYPE_SECTION => '固定时间',
        self::DATE_TYPE_FIXED => '天数',
    ];


    public function setUseBeginTimeAttr($value)
    {
        return strtotime($value);
    }

    public function setUseEndTimeAttr($value)
    {
        return strtotime($value);
    }

    public function setGetBeginTimeAttr($value)
    {
        return strtotime($value);
    }

    public function setGetEndTimeAttr($value)
    {
        return strtotime($value);
    }

    public function getUseBeginTimeAttr($value)
    {
        return date('Y-m-d H:i:s', $value);
    }

    public function getBeginTimeAttr($value)
    {
        return date('Y-m-d', $value);
    }

    public function getEndTimeAttr($value)
    {
        return date('Y-m-d', $value);
    }

    public function getUseEndTimeAttr($value)
    {
        return date('Y-m-d H:i:s', $value);
    }

    public function checkRuleCount($rule)
    {
        return $this->where('rule', $rule)->count();
    }

    /**
     * 检查当前用户是否可以领取当月生日券
     * @param $member_id
     * @return bool
     */
    public static function checkCurrentAllowGetBrithdayCouponByMemberId($member_id)
    {
        $current_month = date('m',time());//获取当前月份
        $brithday = Member::where('id',$member_id)->value('birthday');
        if (empty($brithday))
            return false;
        $time_arr = mFristAndLast(date('Y'),date('m'));
        $num = Coupon::where(['member_id'=>$member_id,'setting_id'=>3,'createtime'=>['between',[$time_arr['firstday'],$time_arr['lastday']]]])->count('id');//查看当月是否已领取过
        if ($num > 0)
            return false;
        $month = date('m',$brithday);
        if ($current_month == $month)
            return true;
        return false;
    }
    /**
     * 检查当前用户是否是新用户
     * @param $member_id
     * @return bool
     */
    public static function checkCurrentAllowGetCouponByMemberId($member_id)
    {
        $info = Order::where(['member_id'=>$member_id,'order_status'=>['between',[2,4]]])->find();
        if (!$info)
            return true;
        return false;
    }


}
